package com.lqg.bookLibrary.common.securityImpl;

import com.alibaba.fastjson2.JSON;
import com.lqg.bookLibrary.common.core.domain.JsonResult;
import com.lqg.bookLibrary.common.core.domain.LoginUser;
import com.lqg.bookLibrary.common.util.JwtUtils;
import com.lqg.bookLibrary.pojo.Users;
import com.lqg.bookLibrary.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录成功的逻辑处理
 * */
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
    @Resource
    private IUsersService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {

        LoginUser userDetails = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //System.out.println(userDetails.toString());
        //System.out.println(userDetails.getUser().toString());
        Users sysUser = userService.lambdaQuery()
                .eq(Users::getUsername, userDetails.getUser().getUsername()).one();

        Map<String,Object> map = new HashMap<>();
        map.put("id",sysUser.getUserId());
        map.put("username",sysUser.getUsername());
        JsonResult result = JsonResult.success(map);
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //httpServletResponse.getWriter().write(result.toString());
        String re = JSON.toJSONString(result);

        String jwt = jwtUtils.generateToken(sysUser.getUserId().toString());
        httpServletResponse.setHeader(jwtUtils.getHeader(), jwt);

        httpServletResponse.getWriter().write(re);
    }
}
